package com.hanxiaozhang.threadbase1ndedition.no98producerandconsumer;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * 〈一句话功能简述〉<br>
 * 〈使用Lock实现生产者与消费者〉
 *
 * @author hanxinghua
 * @create 2021/11/12
 * @since 1.0.0
 */
public class No2UseLock {

    public static void main(String[] args) throws InterruptedException {

        No2Platform platform = new No2Platform();
        // 生产者每10ms生成一个汉堡
        Thread producer = new Thread(() -> {
            for (int i = 0; i < 15; i++) {
                try {
                    Thread.sleep(10);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                platform.increment();
            }
        }, "Producer");
        // 消费者每5ms消耗一个汉堡
        Thread consumer = new Thread(() -> {
            for (int i = 0; i < 15; i++) {
                try {
                    Thread.sleep(5);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                platform.decrement();
            }
        }, "Consumer");

        producer.start();
        TimeUnit.MILLISECONDS.sleep(80);
        consumer.start();
    }

}

class No2Platform {

    private int hamburger = 0;

    private static final int MAX_THRESHOLD = 5;

    private Lock lock = new ReentrantLock();

    private Condition condition = lock.newCondition();


    /**
     * 自增
     */
    public void increment() {

        lock.lock();
        try {
            while (hamburger == MAX_THRESHOLD) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            hamburger++;
            System.out.println("increment hamburger,current is " + hamburger);
            condition.signal();
        } finally {
            lock.unlock();
        }
    }


    /**
     * 自减
     */
    public synchronized void decrement() {

        lock.lock();
        try {
            while (hamburger == 0) {
                try {
                    condition.await();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
            hamburger--;
            System.out.println("decrement hamburger,current is " + hamburger);
            condition.signal();
        } finally {
            lock.unlock();
        }
    }


}